import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Modal, Button, Space, Table, Skeleton, Popconfirm, App } from 'antd';
import { DeleteOutlined, PlusOutlined, SyncOutlined } from '@ant-design/icons';

import TaskForm from './Form.js';
import { getList, deleteById } from '../../apis/task.js';

const CompletedList = forwardRef(({ contentHeight, isHeightReady }, ref) => {
  const { message } = App.useApp();
  useImperativeHandle(ref, ()=>({
    refresh
  }));

  const columns = [
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
      minWidth: 400
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 160,
      render: (value, record) => (
        <Space size='middle'>
          <Button onClick={() => add(record)} type='default' shape='circle' icon={<PlusOutlined/>}/>
          <Popconfirm
            title='确定删除吗'
            onConfirm={()=>{ del(record)}}
            okText="确认"
            cancelText="取消"
          >
            <Button danger type='primary' shape='circle' icon={<DeleteOutlined/>}/>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const [listData, setListData] = useState([]);
  const [formData, setFormData] = useState(null);
  const [isFormOpen, setIsFormOpen] = useState(false);

  useEffect(()=>{
    refresh();
  }, [])

  const refresh = async () => {
    const res = await getList({isCompleted: 1});
    setListData(res.data);
  };

  const add = ({content}) => {
    // console.log('add', value);
    setFormData({content})
    setIsFormOpen(true);
  };

  const del = async ({id}) => {
    const res = await deleteById(id);
    if(res.success){
      await refresh();
      message.success('任务已删除')
    }
  };

  const handleFormCancel = ()=>{
    setIsFormOpen(false);
  }

  return (
    <>
      {/* 按钮组 */}
      <Space style={{ float: 'right', marginBottom: '16px' }}>
        <Button onClick={() => {
          refresh().then(() => {
            message.success('列表已更新');
          });
        }} type='default' shape='circle' icon={<SyncOutlined/>} title={'刷新'}/>
      </Space>

      {/* 弹出表单 */}
      <Modal
        title='模板新增任务'
        open={isFormOpen}
        onCancel={handleFormCancel}
        footer={null}
      >
        <TaskForm formData={formData} listUpdate={()=>{}}></TaskForm>
      </Modal>

      {/* 避免第一次渲染结果回闪 */}
      {!isHeightReady ? (
        <Skeleton active/>
      ) : (
        <Table
          dataSource={listData}
          columns={columns}
          rowKey='id'
          tableLayout={'auto'}
          scroll={{ y: (contentHeight - 200) }}
          pagination={false}
          bordered
        />
      )}

    </>
  );
});

export default CompletedList;
